﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;

using SolrExample.Tests;
using NUnit.Framework;
using Spring.Context;
using Spring.Context.Support;
using SolrExample.Common;
using SolrExample.Interface.DomainObject;
using SolrNet.Impl;
using SolrNet.Commands;
using SolrExample.Tests.SolrClient;
using SolrNet;
using Microsoft.Practices.ServiceLocation;
using SolrNet.Attributes;
using SolrNet.Commands.Parameters;

namespace SolrExample.Tests.Temp
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestFixture]
    public class SolrOperation_Test
    {
        private static SearchEngineCommand mSearchEngine = new SearchEngineCommand();
        [TestFixtureSetUp]
        public void InitializeAllTests()
        {

        }

        [Test]
        public void Test1()
        {
            IApplicationContext applicationContext = ContextRegistry.GetContext();
            JobServices jobServices = applicationContext.GetObject("JobServices") as JobServices;
            jobServices.CommitIndex();
        }

        [Test]
        public void Test2() {
            IList<IPerson> listPerson = new List<IPerson>();
            for (var i = 1; i <= 6; i++)
            {
                IPerson person = new Person() {
                    Id = 1000 + i,
                    CountryCode = "HK",
                    LastModifiedDate = DateTime.Now,
                    Name = "Miragelu" + i
                };
                listPerson.Add(person);
            }
            string hardServices = "HB#http://localhost:8080/solr-HDM";
            string jobsDBTextFieldsStr = "";

            Dictionary<string, Dictionary<string, bool>> postedResult = CreateIndexFromHardCard(listPerson, hardServices, jobsDBTextFieldsStr);
            bool success = null != postedResult.Values.SingleOrDefault(i => i.Values.Contains(true));
            Console.WriteLine("Post result: " + success);

            try
            {
                string searchKey = "name:miragelu1";
                Dictionary<string, bool> deletedResult = DeleteCacheFromSearchKey(searchKey, "HK", hardServices);
                //bool deleted = false != deletedResult.Values.SingleOrDefault(i => i==true);
                //Console.WriteLine("Delte result: " + deleted);
            }
            catch { }

            try { 
                IList<string> Ids = new List<string>(){"10003", "1005"};
                Dictionary<string, bool> deletedIdsResult = DeleteHarddiskFromIds(Ids, "HK", hardServices);
                Console.WriteLine("");
            }
            catch { }
                        
        }

        [Test]
        public void Test3()
        {
            string hardServices = "http://localhost:8080/solr-HDM/HK";
            Startup.Init<JobID>(hardServices);
            var solr = ServiceLocator.Current.GetInstance<ISolrOperations<JobID>>();
            var solrquery1 = new SolrQueryByField("name", "mir");
            var solrquery2 = new SolrQuery("name:mirage AND name:miragelu2");
            var solrquery3 = new SolrQueryByRange<long>("adsid", 100, 103);
            var solrquery4 = new SolrQueryInList("id", "1004", "1005");
            var solrquery5 = new SolrHasValueQuery("name");
            var q1 = new SolrQuery("solr") && new SolrQuery("name:desc"); // can use the && and || operators to concatenate operators with the expected results:
            var q2 = new SolrQuery("solr") + new SolrQuery("name:desc"); //或的关系，两个结果集相加 
            var q3 = new SolrQuery("solr") - new SolrQuery("name:desc"); //包含solr但不包含name=desc
            var q4 = !new SolrQuery("solr"); //you can call Not() on it or just use the '!' operator:
            var q5 = new SolrQuery("solr") + !new SolrQuery("name:desc"); //包含solr但不包含name=desc
            var q6 = solr.Query(new SolrMultipleCriteriaQuery(new[] { new SolrQuery("2222"), new SolrQuery("Leading Soft") })); //与+含义相同
            var q7 = solr.Query(new SolrMultipleCriteriaQuery(new[] { new SolrQuery("2222"), new SolrQuery("myself") }, "AND")); //与&&含义相同
            var q8 = solr.Query(SolrQuery.All);

            //JobID jobID = new JobID();
            //solr.Add(jobID);
            //solr.Commit();

            //solr.Delete(solrquery1)

            var result = solr.Query(solrquery1);
            foreach (JobID jobid in result)
            {
                Console.WriteLine(jobid.Id);
            }
            //Console.WriteLine(result.Count);  
            IList<long> listId = result.Select(i => i.Id).ToList();
            Console.WriteLine(listId[0]);

            var result1 = solr.Query(solrquery1, new QueryOptions()
            {
                Start = 1,   //从指定位置开始
                Rows = 1,   //搜索指定记录信息
                OrderBy = new[]{new SortOrder("id", Order.DESC) },   //排序
                Fields = new[] { "id", "name" }  //只查询出特定的列
            });
            foreach (JobID jobid in result1)
            {
                Console.WriteLine("result1: " + jobid.Id);
            }


            var result2 = solr.Query(solrquery2);
            Console.WriteLine("result2 count: " + result2.Count);


            var result3 = solr.Query(solrquery3);
            Console.WriteLine("result3 count: " + result3.Count);

            var result4 = solr.Query(solrquery4);
            Console.WriteLine("result4 count: " + result4.Count);
        }

        [TestFixtureTearDown]
        public void CleanupAllTests() { }

        /// <summary>
        /// Create Index To Hard Card
        /// </summary>
        /// <param name="jobAds"></param>
        /// <returns></returns>
        public static Dictionary<string, Dictionary<string, bool>> CreateIndexFromHardCard(IList<IPerson> person, string persistantServers, string jobsDBTextFields)
        {
            //step 1: get record index xml.
            Dictionary<string, string> indexFieldXmls = IndexFieldFactory.ComposeIndexFieldXml(person, true, jobsDBTextFields);

            //step 2: post index xml to search engine
            Dictionary<string, Dictionary<string, bool>> postedResult = new Dictionary<string, Dictionary<string, bool>>();
            List<string> searchEngineUrls = persistantServers.Split(';').ToList();
            foreach (string key in indexFieldXmls.Keys)
            {
                //string jobsDBCountryCode = CommonConfig.GetConfigValue("JobsDB_" + key);
                Dictionary<string, bool> methodResults = mSearchEngine.PostXml(searchEngineUrls, indexFieldXmls[key], key, true);
                postedResult[key] = methodResults;
            }
            return postedResult;
        }

        public static Dictionary<string, bool> DeleteCacheFromSearchKey(string searchKey, string jobsDbCountryCode, string cacheServers)
        {
            List<string> searchEngineUrls = cacheServers.Split(';').ToList();
            return mSearchEngine.DeleteSearchKey(searchEngineUrls, searchKey, jobsDbCountryCode, true);
        }

        public static Dictionary<string, bool> DeleteHarddiskFromIds(IList<string> recoreId, string jobsDbCountryCode, string servers)
        {
            Dictionary<string, bool> dicResult = new Dictionary<string, bool>();
            List<string> searchEngineUrls = servers.Split(';').ToList();
            dicResult = mSearchEngine.Delete(searchEngineUrls, recoreId, jobsDbCountryCode, true);
            return dicResult;
        }
    }


    public interface IPerson : IIndexRecord
    {
        string Name { get; set; }
    }
    public class Person : IPerson, IIndexRecord {
        public long Id { get; set; }
        public string CountryCode { get; set; }
        public DateTime LastModifiedDate { get; set; }
        public bool IsSearchableRecord { get { return true; } }

        public string Name { get; set; }
    }


    public class JobID {
        [SolrUniqueKey("id")]
        public long Id{get;set;}
    }
}
